package com.infocollect.project.api.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.infocollect.common.utils.ServletUtils;
import com.infocollect.framework.security.LoginUser;
import com.infocollect.framework.security.service.TokenService;
import com.infocollect.project.api.entity.*;
import com.infocollect.project.api.helper.CurrentHelp;
import com.infocollect.project.api.helper.JSONUtil;
import com.infocollect.project.api.mapper.*;
import com.infocollect.project.api.service.*;
import com.infocollect.project.api.vo.CurrentUserInfoVO;
import com.infocollect.project.api.entity.*;
import com.infocollect.project.api.mapper.TappProcessMapper;
import com.infocollect.project.api.service.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

/**
 * (TappProcess)表服务实现类
 *
 * @author makejava
 * @since 2019-12-25 10:32:30
 */
@Service("tappProcessService")
public class TappProcessServiceImpl extends ServiceImpl<TappProcessMapper, TappProcessEntity> implements ITappProcessService {
    @Autowired
    private TokenService tokenService;
    @Resource
    private ITappActService tappActDao;
    @Resource
    private ITappActDataPermissionService tappActdatapermissionDao;
    @Resource
    private ITappActroutingService tappActroutingDao;
    @Resource
    private ITappActOperatePermissionService tappActoperatepermissionDao;
    @Resource
    private ITappProcessChartService tappProcesschartDao;
    @Resource
    private ITappProcessEmailService tappProcessemailDao;
    /**
     * 通过ID查询单条数据
     *
     * @param fid 主键
     * @return 实例对象
     */
    @Override
    public TappProcessEntity queryById(Long fid) {
        return this.baseMapper.queryById(fid);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit 查询条数
     * @return 对象列表
     */
    @Override
    public List<TappProcessEntity> queryAllByLimit(int offset, int limit) {
        return this.baseMapper.queryAllByLimit(offset, limit);
    }
    /**
     * 流程模板例表查询数据
     * @param entity
     * @param
     * @return
     */
    @Override
    public  List<TappProcessEntity> QueryList(TappProcessEntity entity,Boolean IsAll){
        if(IsAll){
            return this.baseMapper.queryAll(entity) ;
        }else
        {
            return this.baseMapper.queryNewFlowdataAll(entity);
        }
    }
    /**
     * 新增数据
     *
     * @param tappProcess 实例对象
     * @return 实例对象
     */
    @Override
    public TappProcessEntity insert(TappProcessEntity tappProcess) {
        this.baseMapper.insert(tappProcess);
        return tappProcess;
    }

    /**
     * 修改数据
     *
     * @param tappProcess 实例对象
     * @return 实例对象
     */
    @Override
    public TappProcessEntity update(TappProcessEntity tappProcess) {
        this.baseMapper.updateById(tappProcess);
        return this.queryById(tappProcess.getFid());
    }

    /**
     * 通过主键删除数据
     *
     * @param fid 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long fid) {
        return this.baseMapper.deleteById(fid) > 0;
    }

    /**
     * 查询多条数据
     * @menu 根据实体对象是否有值 进行查询
     * @return 对象列表
     */
    @Override
    public List<TappProcessEntity> queryAll(TappProcessEntity entity){
        return this.baseMapper.queryAll(entity) ;
    }

    /**
     *
     * @param processid
     * @return
     */
    @Transactional
    @Override
    public Long  StopFlow(Long processid)throws Exception{
        return CopyFlow(processid,3,null,null);
    }

    /**
     * 启动流程模板
     * @param processid
     * @return
     */
    @Override
    public Long StartFlow(Long processid){
        TappProcessEntity process=new TappProcessEntity();
        process.setFstate(2);
        process.setFid(processid);
        this.baseMapper.updateById(process);
        return processid;
    }

    /**
     * 流程模板另存为
     * @return
     */
    @Override
    public Long SaveAsFlow(Long  processid,String  processname,String processcode)throws Exception{
        return CopyFlow(processid,1,processname,processcode);
    }

    /**
     *  拷贝流程
     * @param processid
     * @param state
     * @param processname
     * @param processcode
     * @return
     * @throws Exception
     */
    long CopyFlow(Long  processid, int state,String  processname,String processcode)throws Exception{
        if(state==1){
            if(processname==null||processname.length()==0)
            {
                throw new Exception("复制流程名称不能空！");
            }
            if(processcode==null||processcode.length()==0)
            {
                throw new Exception("复制流程编码不能空！");
            }
            if(!CheackProcesscode(processcode)){
                throw new Exception("流程编码已经存在！");
            }
        }
        TappProcessEntity oldentity = this.baseMapper.queryById(processid);
//        CurrentUserInfoVO currentUserInfo = CurrentHelp.Ins.GetUser();
        LoginUser currentUserInfo = tokenService.getLoginUser(ServletUtils.getRequest());
        TappProcessEntity entity=new TappProcessEntity();
        entity.setFcreateby(currentUserInfo.getUserName());
        entity.setFlastupdateby(currentUserInfo.getUserName());
        entity.setFcreationdate(new Date());
        entity.setFlastupdatedate(new Date());
        if(state==3) { ///等于3代表是停用操作  停用后将当前流程模板状态改为4
            entity.setFprocesscode(oldentity.getFprocesscode());
            entity.setFprocessname(oldentity.getFprocessname());
            oldentity.setFstate(4);
            entity.setFversion(oldentity.getFversion()+1);
            this.baseMapper.updateById(oldentity);
        }else{
            entity.setFprocesscode(processcode);
            entity.setFprocessname(processname);
            entity.setFversion(1);
        }
        entity.setFprocesstypecode(oldentity.getFprocesstypecode());
        entity.setFisreminder(oldentity.getFisreminder());
        entity.setFisendreminder(oldentity.getFisendreminder());
        entity.setFiscopy(oldentity.getFiscopy());
        entity.setFremindermode(oldentity.getFremindermode());
        entity.setFdescription(oldentity.getFdescription());
        entity.setFstarttype(oldentity.getFstarttype());
        entity.setFstartid(oldentity.getFstartid());
        entity.setFstartname(oldentity.getFstartname());
        entity.setFromid(oldentity.getFromid());
        entity.setFstate(state); /// 1草稿 2启动，3停用
        this.baseMapper.insert(entity);
        TappProcessChartEntity oldprocesschart=this.tappProcesschartDao.queryByProcessId(processid);
        JSONObject json = JSONObject.fromObject(oldprocesschart.getFlowdata());
        JSONObject nodeJsonObject = json.getJSONObject("Node");
        Iterator<String> it = nodeJsonObject.keys();
        while (it.hasNext()) {
            String key = it.next();
            JSONObject actJsonObject = nodeJsonObject.getJSONObject(key);
            if (key.equals("F_End")) {
                continue;
            }
            TappActEntity tappAct=new TappActEntity();  ///保存节点信息
            tappAct.setFcreateby(currentUserInfo.getUserName());
            tappAct.setFlastupdateby(currentUserInfo.getUserName());
            tappAct.setFcreationdate(new Date());
            tappAct.setFlastupdatedate(new Date());
            tappAct.setFprocessid(entity.getFid());
            tappAct.setFactname(actJsonObject.getString("FNodeName"));
            tappAct.setFapprovaltype(actJsonObject.getString("FApprovalType"));
            tappAct.setFactchartid(actJsonObject.getString("FActChartID"));
            if(tappAct.getFapprovaltype()=="2") {
                tappAct.setFapprover(actJsonObject.getString("FApprover"));
                tappAct.setFapprovername(actJsonObject.getString("FApproverName"));
            }else{
                tappAct.setFapprovername("");
                tappAct.setFapprover(actJsonObject.getString("FApprovalObj"));
            }
            tappAct.setFhandlecountersigntype(actJsonObject.getString("FHandleCountersignType"));
            tappAct.setFiscontinuousby(actJsonObject.getBoolean("FIsContinuousBy"));
            tappAct.setFisnotcontinuousby(actJsonObject.getBoolean("FIsNotContinuousBy"));
            tappAct.setFisrejectemail(actJsonObject.getBoolean("FIsRejectEmail"));
            tappAct.setFisrejecthistory(actJsonObject.getBoolean("FIsRejectHistory"));
            tappAct.setFisemail(actJsonObject.getBoolean("FIsEmail"));
            tappAct.setFhandletype(actJsonObject.getString("FHandleType"));
            this.tappActDao.insert(tappAct);
            actJsonObject.put("atctid", tappAct.getFid());
            String datapermissionStr=  JSONUtil.objToJson(actJsonObject.getJSONObject("DataPermission")) ;
            TappActDataPermissionEntity datapermissionentity = new TappActDataPermissionEntity(); // 保存数据权限
            datapermissionentity.setFcreateby(currentUserInfo.getUserName());
            datapermissionentity.setFlastupdateby(currentUserInfo.getUserName());
            datapermissionentity.setFcreationdate(new Date());
            datapermissionentity.setFlastupdatedate(new Date());
            datapermissionentity.setFactdatapermission(datapermissionStr);
            datapermissionentity.setFactid(tappAct.getFid());
            this.tappActdatapermissionDao.insert(datapermissionentity);
            String permissionStr=  JSONUtil.objToJson(actJsonObject.getJSONArray("OperatePermission")) ;
            String attachmentPermissionJosn=  JSONUtil.objToJson(actJsonObject.getJSONArray("AttachmentPermission")) ;
            TappActOperatePermissionEntity operatepermissionItem = new TappActOperatePermissionEntity(); ////保存节点操作权限
            operatepermissionItem.setFcreateby(currentUserInfo.getUserName());
            operatepermissionItem.setFlastupdateby(currentUserInfo.getUserName());
            operatepermissionItem.setFcreationdate(new Date());
            operatepermissionItem.setFlastupdatedate(new Date());
            operatepermissionItem.setFactoperatepermission(permissionStr);
            operatepermissionItem.setFactid(tappAct.getFid());
            operatepermissionItem.setFoperatetype(1);
            this.tappActoperatepermissionDao.insert(operatepermissionItem);
            TappActOperatePermissionEntity operatepermissionItem2 = new TappActOperatePermissionEntity(); ////保存节点操作权限
            operatepermissionItem2.setFcreateby(currentUserInfo.getUserName());
            operatepermissionItem2.setFlastupdateby(currentUserInfo.getUserName());
            operatepermissionItem2.setFcreationdate(new Date());
            operatepermissionItem2.setFlastupdatedate(new Date());
            operatepermissionItem2.setFactoperatepermission(attachmentPermissionJosn);
            operatepermissionItem2.setFactid(tappAct.getFid());
            operatepermissionItem2.setFoperatetype(2);
            this.tappActoperatepermissionDao.insert(operatepermissionItem2);
            JSONArray actRoutingJsonObject= actJsonObject.getJSONArray("Routing");////开始保存路由
            for (int i=0;i<actRoutingJsonObject.size();i++) {
                JSONObject actitemjson=actRoutingJsonObject.getJSONObject(i);
                TappActRoutingEntity routingentity = new TappActRoutingEntity();
                routingentity.setFlastupdateby(currentUserInfo.getUserName());
                routingentity.setFlastupdatedate(new Date());
                routingentity.setFrunactid(actitemjson.getString("nodeID"));
                routingentity.setFactid(tappAct.getFid());
                routingentity.setFrunactname(actitemjson.getString("nodeName"));
                routingentity.setFroutingjson(JSONUtil.objToJson(actitemjson.getJSONArray("routingList")) );
                routingentity.setFexpressionjson(JSONUtil.objToJson(actitemjson.getJSONArray("expressionList")));
                routingentity.setFoutputrules(actitemjson.getString("ruleName"));
                routingentity.setFcreationdate(new Date());
                routingentity.setFcreateby(currentUserInfo.getUserName());
                this.tappActroutingDao.insert(routingentity);
                actitemjson.put("routingid", routingentity.getFid());
            }
        }
        TappProcessChartEntity tappProcesschart = new TappProcessChartEntity();
        tappProcesschart.setFcreateby(currentUserInfo.getUserName());
        tappProcesschart.setFlastupdateby(currentUserInfo.getUserName());
        tappProcesschart.setFcreationdate(new Date());
        tappProcesschart.setFlastupdatedate(new Date());
        tappProcesschart.setFprocessid(entity.getFid());
        tappProcesschart.setFprocesschart(oldprocesschart.getFprocesschart());
        tappProcesschart.setFlowdata(JSONUtil.objToJson(json));
        this.tappProcesschartDao.insert(tappProcesschart);
        List<TappProcessEmailEntity> processemailList=   tappProcessemailDao.queryByProcessID(processid);
        for (int i=0;i<processemailList.size();i++) {
            TappProcessEmailEntity oldemailitem=processemailList.get(i);
            TappProcessEmailEntity emailitem = new TappProcessEmailEntity();
            emailitem.setFcreateby(currentUserInfo.getUserName());
            emailitem.setFlastupdateby(currentUserInfo.getUserName());
            emailitem.setFcreationdate(new Date());
            emailitem.setFlastupdatedate(new Date());
            emailitem.setFemailid(oldemailitem.getFemailid());
            emailitem.setFemailname(oldemailitem.getFemailname());
            emailitem.setFemailtype(oldemailitem.getFemailtype());
            emailitem.setFprocessid(entity.getFid());
            this.tappProcessemailDao.insert(emailitem);
        }
        return entity.getFid();

    }

    ///检查流程编号是否重复
    @Override
    public   Boolean CheackProcesscode(String processcode){
        TappProcessEntity queryprocess=new TappProcessEntity();
        queryprocess.setFprocesscode(processcode);
        List<TappProcessEntity>  processesList= baseMapper.queryAll(queryprocess);
        return !(processesList.size()>0);
    }
    /**
     * 保存流程模板数据
     * @param param
     * @return
     */
    @Override
    @Transactional
    public String SaveFlowData( Map<String, String> param,Integer state) throws IOException {
        String jsonString = param.get("flowJson");///流程表单数据
        String flowdrawStr = param.get("flowdraw"); ///画的图形
        String flowID = param.get("flowID");
        JSONObject json = JSONObject.fromObject(jsonString);
        TappProcessEntity entity = (flowID == null || flowID.length() == 0) ? null : this.baseMapper.queryById(Long.parseLong(flowID));
//        CurrentUserInfoVO currentUserInfo = CurrentHelp.Ins.GetUser();
        LoginUser currentUserInfo = tokenService.getLoginUser(ServletUtils.getRequest());
        System.out.println("TappProcess");
        if (entity == null) {
            entity = new TappProcessEntity();
            entity.setFcreateby(currentUserInfo.getUserName());
            entity.setFlastupdateby(currentUserInfo.getUserName());
            entity.setFcreationdate(new Date());
            entity.setFlastupdatedate(new Date());
            entity.setFprocesscode(json.getString("FlowCode"));
            entity.setFprocessname(json.getString("FlowName"));
            entity.setFbusinessmoduleid(json.getString("BusinessModuleID"));
            entity.setFbusinessmoudle(json.getString("BusinessMoudle"));
            entity.setFprocesstypecode(json.getString("FlowType"));
            entity.setFisreminder(Boolean.parseBoolean(json.getString("FIsEnabledAlert")));
            entity.setFisendreminder(Boolean.parseBoolean(json.getString("FIsAlertStarter")));
            entity.setFiscopy(Boolean.parseBoolean(json.getString("FIsCopyStart")));
            entity.setFremindermode(json.getString("FMessageType"));
            entity.setFdescription(json.getString("FRemark"));
            entity.setFstarttype(json.getString("FStartType"));
            entity.setFstartid(json.getString("FStartPerson"));
            entity.setFstartname(json.getString("FStartPersonName"));
            entity.setFromid(json.getLong("FromID"));
            entity.setFversion(1);
            if(state!=null) {
                entity.setFstate(state); /// 1草稿 2启动，3停用
            } else{
                entity.setFstate(1);
            }
            this.baseMapper.insert(entity);
        } else {
            entity.setFlastupdateby(currentUserInfo.getUserName());
            entity.setFlastupdatedate(new Date());
            entity.setFprocesscode(json.getString("FlowCode"));
            entity.setFprocessname(json.getString("FlowName"));
            entity.setFprocesstypecode(json.getString("FlowType"));
            entity.setFbusinessmoduleid(json.optString("BusinessModuleID"));
            entity.setFbusinessmoudle(json.optString("BusinessMoudle"));
            entity.setFisreminder(Boolean.parseBoolean(json.getString("FIsEnabledAlert")));
            entity.setFisendreminder(Boolean.parseBoolean(json.getString("FIsAlertStarter")));
            entity.setFiscopy(Boolean.parseBoolean(json.getString("FIsCopyStart")));
            entity.setFremindermode(json.getString("FMessageType"));
            entity.setFdescription(json.getString("FRemark"));
            entity.setFstarttype(json.getString("FStartType"));
            entity.setFstartid(json.getString("FStartPerson"));
            entity.setFstartname(json.getString("FStartPersonName"));
            entity.setFromid(json.getLong("FromID"));
            if(state!=null)
                entity.setFstate(state); /// 1草稿 2启动，3停用
            this.baseMapper.updateById(entity);
        }
        SaveProcessEmail(entity.getFid(),json.getJSONArray("EmailConfig"));
        SaveAct(entity.getFid(),json);
        jsonString= JSONUtil.objToJson(json);
        SaveProcesschart(entity.getFid(),flowdrawStr,jsonString);
        Map<String,Object> returnMap=new HashMap<>();
        returnMap.put("flowJson",jsonString);
        returnMap.put("flowID",entity.getFid());
        return JSONUtil.objToJson(returnMap);
    }


    /**
     * 保存节点信息
     * @param proessID
     * @param flowjson  流程json对象
     * @return
     */
    Boolean SaveAct(Long proessID, JSONObject flowjson)throws IOException {
        JSONObject nodeJsonObject = flowjson.getJSONObject("Node");
        Iterator<String> it = nodeJsonObject.keys();
        ///删除对应节点信息
        List<TappActEntity> tappActList=   this.tappActDao.queryByPorcessId(proessID);
        List<Long> updateList=new ArrayList<>();
        while (it.hasNext()) {
            // 获得key
            String key = it.next();
            JSONObject actJsonObject = nodeJsonObject.getJSONObject(key);
            if (key.equals("F_End")) {
                continue;
            }
//            CurrentUserInfoVO currentUserInfo = CurrentHelp.Ins.GetUser();
            LoginUser currentUserInfo = tokenService.getLoginUser(ServletUtils.getRequest());
            TappActEntity tappAct = new TappActEntity();
            //     System.out.println("tappAct："+JackJson.objToJson(actJsonObject));
            if (actJsonObject.get("atctid") == null || actJsonObject.getString("atctid").length() == 0) {
                tappAct.setFcreateby(currentUserInfo.getUserName());
                tappAct.setFlastupdateby(currentUserInfo.getUserName());
                tappAct.setFcreationdate(new Date());
                tappAct.setFlastupdatedate(new Date());
                tappAct.setFprocessid(proessID);
                tappAct.setFactname(actJsonObject.getString("FNodeName"));
                tappAct.setFapprovaltype(actJsonObject.getString("FApprovalType"));
                tappAct.setFactchartid(actJsonObject.getString("FActChartID"));
                if (tappAct.getFapprovaltype().equals("2")) {
                    tappAct.setFapprover(actJsonObject.getString("FApprover"));
                    tappAct.setFapprovername(actJsonObject.getString("FApproverName"));
                } else {
                    tappAct.setFapprovername("");
                    tappAct.setFapprover(actJsonObject.getString("FApprovalObj"));
                }
                tappAct.setFhandlecountersigntype(actJsonObject.getString("FHandleCountersignType"));
                tappAct.setFiscontinuousby(actJsonObject.getBoolean("FIsContinuousBy"));
                tappAct.setFisnotcontinuousby(actJsonObject.getBoolean("FIsNotContinuousBy"));
                tappAct.setFisrejectemail(actJsonObject.getBoolean("FIsRejectEmail"));
                tappAct.setFisrejecthistory(actJsonObject.getBoolean("FIsRejectHistory"));
                tappAct.setFisemail(actJsonObject.getBoolean("FIsEmail"));
                tappAct.setFhandletype(actJsonObject.getString("FHandleType"));
                this.tappActDao.insert(tappAct);
                actJsonObject.put("atctid", tappAct.getFid());
            } else {
                updateList.add(actJsonObject.getLong("atctid"));
                tappAct.setFid(actJsonObject.getLong("atctid"));
                tappAct.setFlastupdateby(currentUserInfo.getUserName());
                tappAct.setFlastupdatedate(new Date());
                tappAct.setFactname(actJsonObject.getString("FNodeName"));
                tappAct.setFapprovaltype(actJsonObject.getString("FApprovalType"));
                tappAct.setFactchartid(actJsonObject.getString("FActChartID"));
                if(tappAct.getFapprovaltype().equals("2")) {
                    tappAct.setFapprover(actJsonObject.getString("FApprover"));
                    tappAct.setFapprovername(actJsonObject.getString("FApproverName"));
                }else{
                    tappAct.setFapprovername("");
                    tappAct.setFapprover(actJsonObject.getString("FApprovalObj"));
                }
                tappAct.setFhandlecountersigntype(actJsonObject.getString("FHandleCountersignType"));
                tappAct.setFiscontinuousby(actJsonObject.getBoolean("FIsContinuousBy"));
                tappAct.setFisnotcontinuousby(actJsonObject.getBoolean("FIsNotContinuousBy"));
                tappAct.setFisrejectemail(actJsonObject.getBoolean("FIsRejectEmail"));
                tappAct.setFisrejecthistory(actJsonObject.getBoolean("FIsRejectHistory"));
                tappAct.setFisemail(actJsonObject.getBoolean("FIsEmail"));
                tappAct.setFhandletype(actJsonObject.getString("FHandleType"));
                this.tappActDao.updateById(tappAct);
            }
            // System.out.println("5");
            SaveOperatePermission(tappAct.getFid(), actJsonObject);
            // System.out.println("6");
            SaveDataPermission(tappAct.getFid(), actJsonObject);
            //  System.out.println("7");
            SaveActrouting(tappAct.getFid(), actJsonObject.getJSONArray("Routing"));
            //  System.out.println("8");
        }
        for (int i=0;i<tappActList.size();i++) {
            TappActEntity delitemact=tappActList.get(i);
            if( !updateList.contains(delitemact.getFid())){
                this.tappActDao.deleteById(delitemact.getFid());
            }
        }
        return true;
    }
    /**
     * 保存节点数据权限
     * @param
     * @param actJsonObject
     * @return
     */
    Boolean SaveDataPermission(Long actID, JSONObject actJsonObject)throws IOException {
        String permissionStr=  JSONUtil.objToJson(actJsonObject.getJSONObject("DataPermission")) ;
        TappActDataPermissionEntity  tappActdatapermission= this.tappActdatapermissionDao.queryByActId(actID);
//        CurrentUserInfoVO currentUserInfo = CurrentHelp.Ins.GetUser();
        LoginUser currentUserInfo = tokenService.getLoginUser(ServletUtils.getRequest());
        if(tappActdatapermission!=null){
            tappActdatapermission.setFlastupdateby(currentUserInfo.getUserName());
            tappActdatapermission.setFlastupdatedate(new Date());
            tappActdatapermission.setFactdatapermission(permissionStr);
            this.tappActdatapermissionDao.updateById(tappActdatapermission);
        }else
        {
            TappActDataPermissionEntity entity = new TappActDataPermissionEntity();
            entity.setFcreateby(currentUserInfo.getUserName());
            entity.setFlastupdateby(currentUserInfo.getUserName());
            entity.setFcreationdate(new Date());
            entity.setFlastupdatedate(new Date());
            entity.setFactdatapermission(permissionStr);
            entity.setFactid(actID);
            this.tappActdatapermissionDao.insert(entity);
            /// actJsonObject.put("dataPermissionid",entity.getFid());
        }
        return true;
    }
    /**
     * 保存节点操作权限
     * @param
     * @param actJsonObject
     * @return
     */
    Boolean SaveOperatePermission(Long actID, JSONObject actJsonObject)throws IOException {
        String permissionStr=  JSONUtil.objToJson(actJsonObject.getJSONArray("OperatePermission")) ;
        String attachmentPermissionJosn=  JSONUtil.objToJson(actJsonObject.getJSONArray("AttachmentPermission")) ;
        List<TappActOperatePermissionEntity> tappActoperatepermissionList=  this.tappActoperatepermissionDao.queryByActId(actID);
//        CurrentUserInfoVO currentUserInfo = CurrentHelp.Ins.GetUser();
        LoginUser currentUserInfo = tokenService.getLoginUser(ServletUtils.getRequest());
        if(tappActoperatepermissionList.size()>0){
            for (Integer i=0;i<tappActoperatepermissionList.size();i++ ) {
                TappActOperatePermissionEntity entity=   tappActoperatepermissionList.get(i);
                if(entity.getFoperatetype().equals(1)){
                    entity.setFlastupdateby(currentUserInfo.getUserName());
                    entity.setFlastupdatedate(new Date());
                    entity.setFactoperatepermission(permissionStr);
                    this.tappActoperatepermissionDao.updateById(entity);
                }else
                {
                    entity.setFlastupdateby(currentUserInfo.getUserName());
                    entity.setFlastupdatedate(new Date());
                    entity.setFactoperatepermission(attachmentPermissionJosn);
                    this.tappActoperatepermissionDao.updateById(entity);
                }
            }
        }else
        {
            TappActOperatePermissionEntity entity = new TappActOperatePermissionEntity();
            entity.setFcreateby(currentUserInfo.getUserName());
            entity.setFlastupdateby(currentUserInfo.getUserName());
            entity.setFcreationdate(new Date());
            entity.setFlastupdatedate(new Date());
            entity.setFactoperatepermission(permissionStr);
            entity.setFactid(actID);
            entity.setFoperatetype(1);
            this.tappActoperatepermissionDao.insert(entity);
            TappActOperatePermissionEntity entity2 = new TappActOperatePermissionEntity();
            entity2.setFcreateby(currentUserInfo.getUserName());
            entity2.setFlastupdateby(currentUserInfo.getUserName());
            entity2.setFcreationdate(new Date());
            entity2.setFlastupdatedate(new Date());
            entity2.setFactoperatepermission(attachmentPermissionJosn);
            entity2.setFactid(actID);
            entity2.setFoperatetype(2);
            this.tappActoperatepermissionDao.insert(entity2);
        }
        return true;
    }

    /**
     * 保存路由信息
     * @param
     * @param actJsonObject
     * @return
     */
    Boolean SaveActrouting(Long actID, JSONArray actJsonObject)throws IOException {
        ///删除对应节点信息
        List<TappActRoutingEntity> tappActList=   this.tappActroutingDao.queryByActID(actID);
        List<Long> updateList=new ArrayList<>();
        LoginUser currentUserInfo = tokenService.getLoginUser(ServletUtils.getRequest());
        for (int i=0;i<actJsonObject.size();i++) {
            JSONObject actitemjson=actJsonObject.getJSONObject(i);
//            CurrentUserInfoVO currentUserInfo = CurrentHelp.Ins.GetUser();
            TappActRoutingEntity entity = new TappActRoutingEntity();
            entity.setFlastupdateby(currentUserInfo.getUserName());
            entity.setFlastupdatedate(new Date());
            entity.setFrunactid(actitemjson.getString("nodeID"));
            entity.setFactid(actID);
            entity.setFrunactname(actitemjson.getString("nodeName"));
            entity.setFroutingjson(JSONUtil.objToJson(actitemjson.getJSONArray("routingList")) );
            entity.setFexpressionjson(JSONUtil.objToJson(actitemjson.getJSONArray("expressionList")));
            entity.setFoutputrules(actitemjson.getString("ruleName"));
            System.out.println("TappActrouting:"+ JSONUtil.objToJson(actitemjson));
            if(actitemjson.get("routingid")==null||actitemjson.getString("routingid").length()==0) {
                entity.setFcreationdate(new Date());
                entity.setFcreateby(currentUserInfo.getUserName());
                this.tappActroutingDao.insert(entity);
                actitemjson.put("routingid", entity.getFid());
            }else{
                updateList.add(actitemjson.getLong("routingid"));
                entity.setFid(actitemjson.getLong("routingid"));
                this.tappActroutingDao.updateById(entity);
            }
        }
        for (int i=0;i<tappActList.size();i++) {
            TappActRoutingEntity delitemactrouting=tappActList.get(i);
            if( !updateList.contains(delitemactrouting.getFid())){
                this.tappActroutingDao.deleteById(delitemactrouting.getFid());
            }
        }
        return true;
    }

    Boolean SaveProcesschart(Long proessID,String flowdraw,String flowData)throws IOException {
        TappProcessChartEntity tappProcesschart=new TappProcessChartEntity();
        tappProcesschart.setFprocessid(proessID);
        List<TappProcessChartEntity> list=this.tappProcesschartDao.queryAll(tappProcesschart);
        if(list!=null&&list.size()>0){
            tappProcesschart=  list.stream().findFirst().get();
        }else
        {
            tappProcesschart=null;
        }
//        CurrentUserInfoVO currentUserInfo = CurrentHelp.Ins.GetUser();
        LoginUser currentUserInfo = tokenService.getLoginUser(ServletUtils.getRequest());
        if(tappProcesschart==null) {
            tappProcesschart = new TappProcessChartEntity();
            tappProcesschart.setFcreateby(currentUserInfo.getUserName());
            tappProcesschart.setFlastupdateby(currentUserInfo.getUserName());
            tappProcesschart.setFcreationdate(new Date());
            tappProcesschart.setFlastupdatedate(new Date());
            tappProcesschart.setFprocessid(proessID);
            tappProcesschart.setFprocesschart(flowdraw);
            tappProcesschart.setFlowdata(flowData);
            this.tappProcesschartDao.insert(tappProcesschart);
        }else{
            tappProcesschart.setFlastupdateby(currentUserInfo.getUserName());
            tappProcesschart.setFlastupdatedate(new Date());
            tappProcesschart.setFprocesschart(flowdraw);
            tappProcesschart.setFlowdata(flowData);
            this.tappProcesschartDao.updateById(tappProcesschart);
        }
        return true;
    }

    /**
     * 保存流程Email
     * @return
     */
    Boolean SaveProcessEmail(Long processid,JSONArray emailConfigJsonArry)throws IOException {
        // tappProcessemailDao.deleteByProcessID(processid);
        ///删除 其他数据
        List<TappProcessEmailEntity> tappProcessemailList=   this.tappProcessemailDao.queryByProcessID(processid);
        List<Long> updateList=new ArrayList<>();
        LoginUser currentUserInfo = tokenService.getLoginUser(ServletUtils.getRequest());
        for (int i=0;i<emailConfigJsonArry.size();i++) {
            JSONObject emailitemjson=emailConfigJsonArry.getJSONObject(i);
//            CurrentUserInfoVO currentUserInfo = CurrentHelp.Ins.GetUser();
            TappProcessEmailEntity entity = new TappProcessEmailEntity();
            entity.setFlastupdateby(currentUserInfo.getUserName());
            entity.setFlastupdatedate(new Date());
            entity.setFemailid(emailitemjson.getLong("EmailID"));
            entity.setFemailname(emailitemjson.getString("EmailName"));
            entity.setFemailtype(emailitemjson.getString("EmailType"));
            entity.setFprocessid(processid );
            if(emailitemjson.get("processemailid")==null||emailitemjson.getString("processemailid").length()==0) {
                entity.setFcreateby(currentUserInfo.getUserName());
                entity.setFcreationdate(new Date());
                this.tappProcessemailDao.insert(entity);
                emailitemjson.put("processemailid", entity.getFid());
            }else{
                updateList.add(emailitemjson.getLong("processemailid"));
                entity.setFid(emailitemjson.getLong("processemailid"));
                this.tappProcessemailDao.updateById(entity);
            }
        }
        for (int i=0;i<tappProcessemailList.size();i++) {
            TappProcessEmailEntity delitemprocessemail=tappProcessemailList.get(i);
            if( !updateList.contains(delitemprocessemail.getFid())){
                this.tappProcessemailDao.deleteById(delitemprocessemail.getFid());
            }
        }
        return true;
    }


}